package pers.qianyu.comment.util;

import com.baomidou.mybatisplus.annotation.*;
import pers.qianyu.comment.pojo.entity.*;

import java.lang.reflect.*;
import java.util.*;

/**
 * 通过 Java 类生成建表语句
 *
 * @author mizzle rain
 * @date 2020-10-11 23:00
 */
public class ClassToSqlUtil {
    public static final Map<String, String> PROPERTY_COLUMN_MAP = new HashMap<>();

    static {
        PROPERTY_COLUMN_MAP.put("Integer", "int");
        PROPERTY_COLUMN_MAP.put("Short", "tinyint");
        PROPERTY_COLUMN_MAP.put("Long", "bigint");
        PROPERTY_COLUMN_MAP.put("BigDecimal", "decimal(19,2)");
        PROPERTY_COLUMN_MAP.put("Double", "double precision not null");
        PROPERTY_COLUMN_MAP.put("Float", "float");
        PROPERTY_COLUMN_MAP.put("Boolean", "bit");
        PROPERTY_COLUMN_MAP.put("Timestamp", "datetime");
        PROPERTY_COLUMN_MAP.put("LocalDateTime", "datetime");
        PROPERTY_COLUMN_MAP.put("String", "varchar(255)");
    }

    public static void main(String[] args) {
        String sql = generateSql(CommentPO.class);
        System.out.println(sql);
    }

    public static String generateSql(Class<?> clazz) {
        String tableName;
        TableName ann = clazz.getAnnotation(TableName.class);
        if (Objects.nonNull(ann)) {
            tableName = ann.value();
        } else {
            tableName = clazz.getSimpleName();
        }
        StringBuilder sql = new StringBuilder();
        sql.append(String.format("drop table if exists `%s`; \r\ncreate table %s(\r\n", tableName, tableName));
        Field[] fields = clazz.getDeclaredFields();
        for (Field field : fields) {
            String fieldName = field.getName();
            if ("serialVersionUID".equals(fieldName)) {
                continue;
            }
            String fieldTypeName = field.getType().getSimpleName();
            sql.append(String.format("\t%s %s", camelToUnderline(fieldName), PROPERTY_COLUMN_MAP.get(fieldTypeName)));
            TableId tableId = field.getAnnotation(TableId.class);
            if (Objects.nonNull(tableId)) {
                sql.append(" primary key auto_increment");
            }
            sql.append(",\r\n");
        }
        sql.delete(sql.length() - 3, sql.length() - 1);
        sql.append(")engine = innodb default charset = utf8mb4;\r\n");
        return sql.toString();
    }

    private static String camelToUnderline(String name) {
        StringBuffer newName = new StringBuffer();
        char[] arr = name.toCharArray();
        for (int i = 0; i < arr.length; i++) {
            int ch = arr[i];
            if (ch >= 65 && ch <= 90) {
                newName.append("_").append((char) (ch + 32));
            } else {
                newName.append(arr[i]);
            }
        }
        return newName.toString();
    }
}
